import {
  app,
  BrowserWindow,
  ipcMain,
  type WebContentsPrintOptions,
} from 'electron';
import path from 'path';
import os from 'os';
import { fileURLToPath } from 'url';
import { postRequest } from './http';
import { usePrintHooks } from './hooks/usePrintHooks';

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
// needed in case process is undefined under Linux
const platform = process.platform || os.platform();

const currentDir = fileURLToPath(new URL('.', import.meta.url));

let mainWindow: BrowserWindow | undefined;

// 主线程调用接口，渲染进程接收数据
async function getRequest(mainWindow: BrowserWindow) {
  try {
    const dataParams = { captchaType: 'blockPuzzle' };
    // const urlPath = 'https://api.saas.test.tynd.com/tyndall-saas/admin-api/v1/system/captcha/get';
    const urlPath =
      'https://gw-yxm.liangkebang.net/vcc/usercenter/captcha_type';
    const beforeData = await postRequest(urlPath, dataParams);
    mainWindow.webContents.send('before-data', beforeData);
  } catch (error: any) {
    mainWindow.webContents.send('before-data', {
      code: 1,
      message: error.message,
    });
  }
}

function createWindow() {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    icon: path.resolve(currentDir, 'icons/icon.png'), // tray icon
    width: 1000,
    height: 600,
    useContentSize: true,
    webPreferences: {
      contextIsolation: true,
      // More info: https://v2.quasar.dev/quasar-cli-vite/developing-electron-apps/electron-preload-script
      preload: path.resolve(
        currentDir,
        path.join(
          process.env.QUASAR_ELECTRON_PRELOAD_FOLDER,
          'electron-preload' + process.env.QUASAR_ELECTRON_PRELOAD_EXTENSION,
        ),
      ),
    },
  });

  process.env.ELECTRON_ENABLE_SECURITY_WARNINGS;
  if (process.env.DEV) {
    mainWindow.loadURL(process.env.APP_URL);
  } else {
    mainWindow.loadFile('index.html');
  }

  getRequest(mainWindow);

  const contents = mainWindow?.webContents;
  ipcMain.on('get-user', () => {
    getRequest(mainWindow as any);
  });

  ipcMain.handle('get:printer', async () => {
    return contents?.getPrintersAsync();
  });

  usePrintHooks({ mainWindow });

  ipcMain.on('set-printer', (_event, printerInfo) => {
    console.log('=============>主进程打印机参数', printerInfo);
    contents?.print(
      printerInfo as WebContentsPrintOptions,
      (success, errorType) => {
        if (!success) console.log(errorType);
      },
    );
  });

  if (process.env.DEBUGGING) {
    // if on DEV or Production with debug enabled
    mainWindow.webContents.openDevTools();
  } else {
    // we're on production; no access to devtools pls
    mainWindow.webContents.on('devtools-opened', () => {
      mainWindow?.webContents.closeDevTools();
    });
  }

  mainWindow.on('closed', () => {
    mainWindow = undefined;
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === undefined) {
    createWindow();
  }
});
